import sensor, image, time,lcd
from time import sleep
from os import listdir
from math import floor,ceil
from gc import collect
from button import BUTTON
from findpyfile import FINDPYFILE
global click_timer
global icon_W,icon_H
global py_file_quantity,py_file_names
global img_homepage,icon_mask,number,size
global select,last_select,exec_file

icon_W=36
icon_H=48
lcd_W=128
lcd_H=160
icon_S=icon_W-5
icon_N=3
#lcd.init(type=2,width=240,height=320)
button=BUTTON()
pyfile=FINDPYFILE()
py_file_quantity=pyfile.py_file_quantity
py_file_names=pyfile.py_file_names
icon_mask=sensor.alloc_extra_fb(icon_W,icon_H,sensor.RGB565)
img_homepage = sensor.alloc_extra_fb(lcd_W,lcd_H,sensor.RGB565)
def cut_round_corners(img,r=10):
    img.draw_circle(r,r,r,fill=True)
    img.draw_circle(icon_W-r,r,r,fill=True)
    img.draw_circle(r,icon_W-r,r,fill=True)
    img.draw_circle(icon_W-r,icon_W-r,r,fill=True)
    img.draw_rectangle(r,0,icon_W-r*2,icon_W,fill=True)
    img.draw_rectangle(0,r,icon_W,icon_W-r*2,fill=True)
    img.draw_rectangle(0,icon_W,icon_W,icon_H-icon_W,fill=True)
def draw_icon(m,s,erase=True):
    global img_homepage,r,number,size,n
    number=m
    size=s
    if size>icon_W:size=icon_W
    elif size<10:size=10
    try:
        if erase:
            img_homepage.draw_rectangle((number%icon_N)*(icon_H-5),floor(number/icon_N)*icon_H,icon_W,icon_H,color=(0,0,0),fill=True)
        exec('img_homepage.draw_image(icon'+str(number)+',(number%icon_N)*(icon_H-5)+round((icon_W-size)/2),floor(number/icon_N)*icon_H+round((icon_W-size)/2),x_size=size,y_size=size+icon_H-icon_W)')
    except:
        pass
for n in range(py_file_quantity):
    exec('icon'+str(n)+'=sensor.alloc_extra_fb(icon_W,icon_H,sensor.RGB565)')
    try:
        exec("icon"+str(n)+".draw_image(image.Image('/ICONS/"+py_file_names[n]+".bmp',copy_to_fb=True), 0,0,x_size=icon_W,y_size=icon_W)")
    except:
        try:
            exec("icon"+str(n)+".draw_image(image.Image('/ICONS/unknow_program.bmp',copy_to_fb=True), 0,0,x_size=icon_W,y_size=icon_W)")
        except:
            exec('icon'+str(n)+'.draw_rectangle(0,0,icon_W,icon_W,fill=True)')
    cut_round_corners(icon_mask,1)
    exec('icon'+str(n)+'.b_and(icon_mask)')
    if len(py_file_names[n])<10:
        exec('icon'+str(n)+'.draw_string(round((10-len(py_file_names[n]))*2),icon_W+2,py_file_names[n],scale=1.0,x_spacing=1,mono_space=False)')
    elif len(py_file_names[n])>=10:
        exec('icon'+str(n)+'.draw_string(0,icon_W+2,py_file_names[n][:9]+"..",scale=1.0,x_spacing=1,mono_space=False)')
for number in range(py_file_quantity):
    draw_icon(number,icon_S)
exec_file=[]
for n in range(0,py_file_quantity):
    exec_file.append(open('/%s.py'%str(py_file_names[n])).read())

#sd.deinit()
lcd.init()
lcd.clear()
draw_icon(1,icon_W)
lcd.display(img_homepage)
def pyselect():
    global last_select,select
    button.key_event=0
    click_timer=time.ticks_ms()
    while True:
        button.event()
        if button.state():
            while button.state():  pass
            if time.ticks_ms()-click_timer>1000:
                break
            if time.ticks_ms()-click_timer<200:
                select=select+1
                if select >= py_file_quantity:  select=0
                if select!=last_select:
                    draw_icon(select,icon_W)
                    draw_icon(last_select,icon_S)
                    last_select=select
                    lcd.display(img_homepage)
        else:
            click_timer=time.ticks_ms()
    while button.state():  pass
    try:
        print('exec start:/'+str(py_file_names[select]))
        exec(exec_file[select])
        gc.collect()
        print('exec end:/'+str(py_file_names[select]))
    except Exception as err:
        img_homepage.draw_string(0,140,'ERR:'+str(err),scale=1.0,x_spacing=1,mono_space=False,color=(139,0,255))
        lcd.display(img_homepage)
        print('ERR:'+str(err))
        while not button.state():  pass
        img_homepage.draw_rectangle(0,140,128,20,color=(0,0,0),fill=True)
    while button.state():  pass
    for number in range(py_file_quantity):
        draw_icon(number,icon_S)
    draw_icon(select,icon_W)
    lcd.display(img_homepage)
select=1
last_select=1
click_timer=time.ticks_ms()
while True:
    if button.state():
        pyselect()
    else:
        click_timer=time.ticks_ms()
